<template>
  <div>
    <el-form :model="form" label-width="auto" inline>
      <el-form-item label="提交时间:">
        <el-date-picker v-model="times" type="datetimerange" start-placeholder="开始时间" value-format="x"
          end-placeholder="结束时间" time-format="A hh:mm:ss" />
      </el-form-item>
      <el-form-item label="收货仓库:">
        <el-select v-model="form.warehouseId">
          <el-option label="全部" :value="0"></el-option>
          <el-option :label="item.value" :value="item.key" v-for="item in store.godownHouseArr" clearable
            :key="item.key" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
        <el-button @click="onSubmit">一键采购</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table ref="multipleTableRef" :data="tableData" style="width: 1500px" @selection-change="handleSelectionChange"
      border>
      <el-table-column type="selection" width="55" />
      <el-table-column label="收货仓库" width="180">
        <template #default="scope">{{ scope.row.warehouseName }}</template>
      </el-table-column>
      <el-table-column width="180">
        <template #header>
          <span>提交时间</span>
          <el-icon @click="SortBtn">
            <Sort />
          </el-icon>
        </template>
        <template #default="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column label="商品信息" width="180">
        <template #default="scope">
          {{ scope.row.skuInfo }}</template>
      </el-table-column>
      <el-table-column label="店铺商品ID" width="180">
        <template #default="scope">
          {{ scope.row.shopGoodId }}</template>
      </el-table-column>
      <el-table-column label="需要采购件数" width="180">
        <template #default="scope">{{ scope.row.purchaseNum }}</template>
      </el-table-column>
      <el-table-column label="备注" width="180">
        <template #default="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button link type="primary" size="small" @click.prevent="toPurchase(scope.row)">
            去采购
          </el-button>
          <el-button link type="primary" size="small" @click.prevent="GeneratePurchaseOrder(scope.row)">
            手动关联
          </el-button>
          <el-button link type="primary" size="small" @click.prevent="PurchaseSet(scope.row)">
            采购链接
          </el-button>
          <el-button link type="primary" size="small" @click.prevent="delectcontent(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="page">
    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <div>
    <el-dialog v-model="HeaddialogVisible" width="500">
      <span>
        <el-form :model="HeaddialogVisibleForm" label-width="auto" style="max-width: 600px"
          ref="HeaddialogVisibleRuleFormRef" :rules="rules">

          <el-form-item label="采购平台：" prop="purchasePlatformId">
            <el-select v-model="HeaddialogVisibleForm.purchasePlatformId">
              <el-option :label="item.value" :value="item" value-key="key"
                v-for="item in store.productPurchaseProcessCreatePurchaseProcessDicArr" :key="item.key"
                @click="getSon(item)" />
            </el-select>
          </el-form-item>
          <el-form-item label="采购账号：" prop="purchaseCustomerId">
            <el-select v-model="HeaddialogVisibleForm.purchaseCustomerId">
              <el-option :label="item.value" :value="item" value-key="key" v-for="item in sonSelect" :key="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="采购订单号：" prop="productPurchaseOrderCode">
            <el-input v-model="HeaddialogVisibleForm.productPurchaseOrderCode" />
          </el-form-item>
          <el-form-item label="采购运单号：" prop="name">
            <el-input v-model="HeaddialogVisibleForm.name" placeholder="多个上家运单号用逗号分隔" />
          </el-form-item>
        </el-form>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm(HeaddialogVisibleRuleFormRef)">取消</el-button>
          <el-button type="primary" @click="confirmHeaddialogVisible(HeaddialogVisibleRuleFormRef)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 采购 -->
  <div>
    <el-dialog v-model="toPurchaseDialogVisible" width="1350">
      <span>
        <el-form :model="toPurchaseDialogVisibleForm" inline>
          <el-form-item label="备注:">
            <el-input v-model="toPurchaseDialogVisibleForm.remark" />
          </el-form-item>
          <el-form-item label="链接:">
            <el-input v-model="toPurchaseDialogVisibleForm.orderUrl" />
          </el-form-item>
          <el-form-item label="平台:">
            <el-select v-model="toPurchaseDialogVisibleForm.PT">
              <el-option :label="item.value" :value="item.key" v-for="item in store.procurementPlatformDicTable"
                :key="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="skuId:">
            <el-input v-model="toPurchaseDialogVisibleForm.skuId" />
          </el-form-item>
          <el-form-item>
            <!-- <el-button>下单</el-button> -->
            <el-button type="primary" @click="submintORxiadan">保存链接并下单</el-button>
            <el-button type="primary" @click="deleteRowTo(multipleSelection)">批量删除</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="toPurchaseTableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="备注" width="120">
            <template #default="scope">{{ scope.row.remark }}</template>
          </el-table-column>
          <el-table-column label="采购链接" width="320">
            <template #default="scope">{{ scope.row.orderUrl }}</template>
          </el-table-column>
          <el-table-column label="skuid" width="120">
            <template #default="scope">{{ scope.row.skuId }}</template>
          </el-table-column>
          <el-table-column label="始发省市" width="120">
            <template #default="scope"> <span @click='openAddCity(scope.row)'>{{ scope.row.state }}</span> </template>
          </el-table-column>
          <el-table-column label="发货快递" width="120">
            <template #default="scope">{{ scope.row.orderLogisticsCompany }}</template>
          </el-table-column>
          <el-table-column label="默认" width="120">
            <template #default="scope">{{ scope.row.isDefault ? '是' : '否' }}</template>
          </el-table-column>
          <el-table-column label="采购价" width="120">
            <template #default="scope">{{ scope.row.purchasePrice }}</template>
          </el-table-column>
          <el-table-column label="添加时间" width="120">
            <template #default="scope">{{ scope.row.createTime }}</template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" @click.prevent="upOrder(scope.row)">
                下单
              </el-button>
              <el-button link type="primary" size="small" @click.prevent="newupOrder(scope.row)">
                下单(测试慎用)
              </el-button>
              <el-button link type="primary" size="small" @click.prevent="deleteRowTo(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </span>
    </el-dialog>
  </div>
  <!-- 添采购 -->
  <div>
    <el-dialog v-model="setPurchaseDialogVisible" width="1350">
      <span>
        <el-form :model="setPurchaseDialogVisibleForm" inline>
          <el-form-item label="备注:">
            <el-input v-model="setPurchaseDialogVisibleForm.remark" />
          </el-form-item>
          <el-form-item label="链接:">
            <el-input v-model="setPurchaseDialogVisibleForm.orderUrl" />
          </el-form-item>
          <el-form-item label="平台:">
            <el-select v-model="setPurchaseDialogVisibleForm.PT">
              <el-option :label="item.value" :value="item.key" v-for="item in store.procurementPlatformDicTable"
                :key="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="skuId:">
            <el-input v-model="setPurchaseDialogVisibleForm.skuId" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitLink">保存链接</el-button>
            <el-button type="primary" @click="deleteRow(multipleSelection)">批量删除</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="setPurchaseTableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="备注" width="120">
            <template #default="scope">{{ scope.row.remark }}</template>
          </el-table-column>
          <el-table-column label="采购链接" width="320">
            <template #default="scope">{{ scope.row.orderUrl }}</template>
          </el-table-column>
          <el-table-column label="skuid" width="120">
            <template #default="scope">{{ scope.row.skuId }}</template>
          </el-table-column>
          <el-table-column label="始发省市" width="120">
            <template #default="scope">{{ scope.row.state }}</template>
          </el-table-column>
          <el-table-column label="发货快递" width="120">
            <template #default="scope">{{ scope.row.orderLogisticsCompany }}</template>
          </el-table-column>
          <el-table-column label="默认" width="120">
            <template #default="scope">{{ scope.row.isDefault ? '是' : '否' }}</template>
          </el-table-column>
          <el-table-column label="采购价" width="120">
            <template #default="scope">{{ scope.row.purchasePrice }}</template>
          </el-table-column>
          <el-table-column label="添加时间" width="120">
            <template #default="scope">{{ scope.row.createTime }}</template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </span>
    </el-dialog>
  </div>
  <!-- 始发地 -->
  <div>
    <el-dialog v-model="CitydialogVisible" width="500">
      <span>
        <el-select v-model="citySetForm.stateUser" placeholder="省" style="width: 280px;" clearable value-key="id">
          <el-option :label="item.name" :value="item.name" v-for="item in province" :key="item.id" />
        </el-select>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="CitydialogVisible = false">取消</el-button>
          <el-button type="primary" @click="CitydialogVisibleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, reactive } from 'vue'
import { useAlertsStore } from '@/store/index'
import { productPurchaseOrderList, productPurchaseProcessCreatePurchaseProcess, productPurchaseLinktaskcreat, productPurchaseLinklist, productPurchaseLinkcreate, productPurchaseLinkdeleteBatch, sysPcaDataList, productPurchaseLinkupdate, taskcreat, removeSubOrder } from '@/api/index'
import { ElMessage } from 'element-plus'
const store = useAlertsStore()
// do not use same name with ref
const form = ref({
  createTimeStart: '',
  createTimeEnd: '',
  userId: 0,
  purchaseStatus: 1,
  createTimeOrder: 0,
  warehouseId: 0,
  pageSize: 10,
  pageNum: 1
})
const times = ref('')
const tableData = ref([])
onBeforeMount(() => {
  getList()
  store.godownHouse()
  store.procurementPlatformDicApi()
})
const onSubmit = () => {
  console.log('submit!')
  form.value.createTimeOrder = 0
  getList()
}
const getList = () => {
  if (times.value) {
    form.value.createTimeStart = times.value[0]
    form.value.createTimeEnd = times.value[1]
  } else {
    form.value.createTimeStart = ''
    form.value.createTimeEnd = ''
  }
  productPurchaseOrderList(form.value).then(res => {
    const { data: { data } } = res
    total.value = data.total
    tableData.value = data.list
  })
}
// 分页
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  form.value.pageSize = val
  getList()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  form.value.pageNum = val
  getList()
}

// table
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 关联
const HeaddialogVisibleForm = ref({})
const HeaddialogVisible = ref(false)
const GeneratePurchaseOrder = (row) => {
  HeaddialogVisible.value = true
  HeaddialogVisibleForm.value.id = row.id
  store.productPurchaseProcessCreatePurchaseProcessDicBtn()
}
// 处理字符串
const removeNonCommaCharacters = (inputString) => {
  // 使用正则表达式匹配非逗号字符并替换为空字符串
  const cleanedString = inputString.replace(/[^,]/g, '')
  return cleanedString
}

const sonSelect = ref([])
const getSon = (item) => {
  sonSelect.value = item.purchaseCustomerDics
  console.log(sonSelect.value)
}
const HeaddialogVisibleRuleFormRef = ref()
const rules = reactive({
  name: [
    { required: true, message: '必填', trigger: 'blur' }
  ],
  productPurchaseOrderCode: [
    { required: true, message: '必填', trigger: 'blur' }
  ],
  purchasePlatformId: [
    {
      required: true,
      message: '必选',
      trigger: 'change'
    }
  ],
  purchaseCustomerId: [
    {
      required: true,
      message: '必选',
      trigger: 'change'
    }
  ]
})
const confirmHeaddialogVisible = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const result = removeNonCommaCharacters(HeaddialogVisibleForm.value.name)
      console.log(result)
      productPurchaseProcessCreatePurchaseProcess({
        productPurchaseProcessCreatList: [
          {
            productPurchaseSubOrderId: HeaddialogVisibleForm.value.id,
            purchasePlatformId: HeaddialogVisibleForm.value.purchasePlatformId.key,
            purchasePlatformName: HeaddialogVisibleForm.value.purchasePlatformId.value,
            purchaseCustomerId: HeaddialogVisibleForm.value.purchaseCustomerId.key,
            purchaseCustomerName: HeaddialogVisibleForm.value.purchaseCustomerId.value,
            productPurchaseOrderCode: HeaddialogVisibleForm.value.productPurchaseOrderCode,
            trackingNumbers: HeaddialogVisibleForm.value.name
          }
        ]
      }).then(res => {
        HeaddialogVisible.value = false
        getList()
        ElMessage.success('操作成功')
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  HeaddialogVisible.value = false
  HeaddialogVisibleForm.value = {}
}
// 去采购
const toPurchaseDialogVisible = ref(false)
const toPurchaseDialogVisibleForm = ref({})
const toPurchaseTableData = ref([])
const toPurchase = (row) => {
  toPurchaseDialogVisibleForm.value.productId = row.productId
  console.log('row')
  console.log(row.id)
  shopListID.value.id = row.id
  productPurchaseLinklist({ productId: row.productId }).then(res => {
    toPurchaseDialogVisible.value = true
    const { data: { data } } = res
    toPurchaseTableData.value = data
  })
}

const setPurchaseDialogVisible = ref(false)
const setPurchaseDialogVisibleForm = ref({})
const setPurchaseTableData = ref([])
// const purOpen = (row) => {
//   setPurchaseDialogVisibleForm.value.productId = row.productId
//   // toPurchaseDialogVisibleForm.value.productId = row.productId
//   productPurchaseLinklist({ productId: row.productId }).then(res => {
//     setPurchaseDialogVisible.value = true

//     const { data: { data } } = res
//     setPurchaseTableData.value = data
//   })
// }
const PurchaseSet = (row) => {
  setPurchaseDialogVisibleForm.value.productId = row.productId
  // toPurchaseDialogVisibleForm.value.productId = row.productId
  productPurchaseLinklist({ productId: row.productId }).then(res => {
    setPurchaseDialogVisible.value = true

    const { data: { data } } = res
    setPurchaseTableData.value = data
  })
}
const deleteRow = (row) => {
  const ids = []
  if (Object.prototype.toString.call(row) === '[object Object]') {
    console.log(row)
    productPurchaseLinkdeleteBatch([row.id]).then(res => {
      ElMessage.success('操作成功')
      console.log('setPurchaseDialogVisibleForm.value.productId')
      console.log(setPurchaseDialogVisibleForm.value.productId)
      PurchaseSet(setPurchaseDialogVisibleForm.value)
    })
  } else if (Object.prototype.toString.call(row) === '[object Array]') {
    console.log(row)
    multipleSelection.value.forEach(e => {
      ids.push(e.id)
    })
    productPurchaseLinkdeleteBatch(ids).then(res => {
      ElMessage.success('操作成功')
      PurchaseSet(setPurchaseDialogVisibleForm.value)
    })
  }
}
const deleteRowTo = (row) => {
  const ids = []
  if (Object.prototype.toString.call(row) === '[object Object]') {
    console.log(row)
    productPurchaseLinkdeleteBatch([row.id]).then(res => {
      ElMessage.success('操作成功')
      console.log('toPurchaseDialogVisibleForm.value.productId')
      console.log(toPurchaseDialogVisibleForm.value.productId)
      toPurchase(toPurchaseDialogVisibleForm.value)
    })
  } else if (Object.prototype.toString.call(row) === '[object Array]') {
    console.log(row)
    multipleSelection.value.forEach(e => {
      ids.push(e.id)
    })
    productPurchaseLinkdeleteBatch(ids).then(res => {
      ElMessage.success('操作成功')
      toPurchase(toPurchaseDialogVisibleForm.value)
    })
  }
}
const onSubmitLink = () => {
  productPurchaseLinkcreate(
    {
      productId: setPurchaseDialogVisibleForm.value.productId,
      remark: setPurchaseDialogVisibleForm.value.remark,
      orderUrl: setPurchaseDialogVisibleForm.value.orderUrl,
      skuId: setPurchaseDialogVisibleForm.value.skuId,
      procurementPlatformId: setPurchaseDialogVisibleForm.value.PT
    }
  ).then(res => {
    ElMessage.success('操作成功')
    PurchaseSet(setPurchaseDialogVisibleForm.value)
  })
}
const shopListID = ref(({
  id: ''
}))
const upOrder = (row) => {
  productPurchaseLinktaskcreat(
    {
      purchaseTasks: [
        {
          productPurchaseOrderDetailId: shopListID.value.id,
          linkId: row.id
        }]
    }
  ).then(res => {
    const { data: { data } } = res
    console.log('')
    location.href = `cg://purchase?mode=purchaseOrder&taskId=${data}`
    // window.location.replace(`cg://purchase?mode=purchaseOrder&taskId=${data}`)
  })
}
const newupOrder = (row) => {
  taskcreat(
    {
      purchaseTasks: [
        {
          productPurchaseOrderDetailId: shopListID.value.id,
          linkId: row.id
        }]
    }
  ).then(res => {
    const { data: { data } } = res
    console.log(`cg://purchase?taskType=purchaseOrder&api=${data}`)
    location.href = `cg://purchase?taskType=purchaseOrder&api=${data}`
    // window.location.replace(`cg://purchase?mode=purchaseOrder&taskId=${data}`)
  })
}
const submintORxiadan = () => {
  productPurchaseLinkcreate(
    {
      productId: toPurchaseDialogVisibleForm.value.productId,
      remark: toPurchaseDialogVisibleForm.value.remark,
      orderUrl: toPurchaseDialogVisibleForm.value.orderUrl,
      skuId: toPurchaseDialogVisibleForm.value.skuId,
      procurementPlatformId: toPurchaseDialogVisibleForm.value.PT
    }
  ).then(res => {
    ElMessage.success('操作成功')
    productPurchaseLinklist({ productId: toPurchaseDialogVisibleForm.value.productId }).then(res => {
      toPurchaseDialogVisible.value = true
      const { data: { data } } = res
      toPurchaseTableData.value = data
      console.log('toPurchaseTableData.value')
      console.log(toPurchaseTableData.value[toPurchaseTableData.value.length - 1])
    })
    // PurchaseSet()
    productPurchaseLinktaskcreat(
      {
        purchaseTasks: [
          {
            productPurchaseOrderDetailId: shopListID.value.id,
            linkId: toPurchaseTableData.value[toPurchaseTableData.value.length - 1].id
          }]
      }
    ).then(res => {
      const { data: { data } } = res
      console.log('')
      location.href = `cg://purchase?mode=purchaseOrder&taskId=${data}`
    })
  })
}

// 修改始发地
const province = ref([])
const citySetForm = {
  id: '',
  stateUser: ''
}
const CitydialogVisible = ref(false)
const openAddCity = (row) => {
  citySetForm.value.id = row.id
  console.log(row)
  sysPcaDataListSelect({ id: 0 }, '省')
  CitydialogVisible.value = true
}

const sysPcaDataListSelect = (val) => {
  console.log(val)
  sysPcaDataList(val.id).then(res => {
    console.log(res)
    const { data: { data } } = res
    province.value = data
  })
}
const CitydialogVisibleSubmit = () => {
  productPurchaseLinkupdate(citySetForm.value).then(res => {
    ElMessage.success('操作成功')
    CitydialogVisible.value = false
  })
}

// table排序
const or = ref(1)
const SortBtn = () => {
  console.log('排序')
  if (or.value === 1) {
    or.value = 2
  } else if (or.value === 2) {
    or.value = 1
  }

  form.value.createTimeOrder = or.value
  getList()

  // shopLIst(form.value).then(res => {
  //   const { data: { data } } = res
  //   total.value = data.total
  //   tableData.value = data.list
  //   loading.value = false
  // })
}
const delectcontent = (row) => {
  removeSubOrder(row.id).then(res => {
    getList()
    ElMessage.success('操作成功')
  })
}
</script>

<style lang='less' scoped></style>
